package com.shishi.fast.common.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shishi.fast.common.annotation.IgnoreJwtVerify;
import com.shishi.fast.common.annotation.ReqPermissions;
import com.shishi.fast.common.constant.LogType;
import com.shishi.fast.common.exception.ApiException;
import com.shishi.fast.common.util.IpUtil;
import com.shishi.fast.common.util.JwtTokenUtil;
import com.shishi.fast.common.vo.ResultCode;
import com.shishi.fast.common.vo.SysLogVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类描述：系统日志，切面处理类
 * Created by liuhaifeng on 2022/3/17.
 */
@Slf4j
@Aspect
@Component
public class ControllerAspect {

    @Pointcut("execution(* com.shishi.fast.*.controller..*.*(..))")
    public void controllerPointCut() {
    }

    @Pointcut("@annotation(com.shishi.fast.common.annotation.LoginLog)")
    public void logLoginPointCut() {
    }

    @Around("controllerPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            //获取request
            HttpServletRequest request = attributes.getRequest();
            log.info("请求信息：- {} - {} - {} , params：- {}", request.getMethod(), request.getServerName(), request.getRequestURI(), request.getQueryString());

            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            //忽略token 验证
            IgnoreJwtVerify ignoreJwtVerify = method.getAnnotation(IgnoreJwtVerify.class);
            if (ignoreJwtVerify == null) {
                // token 验证
                if (!JwtTokenUtil.validateToken(request)) {
//                    throw new ApiException(ResultCode.UNAUTHORIZED);
                }
            }
            ReqPermissions reqPermissions = method.getAnnotation(ReqPermissions.class);
            if (reqPermissions != null) {
                //日志
                if (reqPermissions.isLog()) {
                    long beginTime = System.currentTimeMillis();
                    //执行方法
                    Object result = joinPoint.proceed();
                    //保存操作成功日志
                    saveSysOperationLog(joinPoint, beginTime, reqPermissions.operation(), request);
                    return result;
                }
            }
        }
        return joinPoint.proceed();
    }

    /**
     * 保存操作日志
     */
    private void saveSysOperationLog(ProceedingJoinPoint joinPoint, long beginTime, String
            operation, HttpServletRequest request) {
        SysLogVO sysLogVO = universalVOLoading(joinPoint, operation, request);
        sysLogVO.setType(LogType.OPERATION.getType());
        sysLogVO.setStatus(1);
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        sysLogVO.setTime(time);
    }

    /**
     * 保存异常日志
     */
    @AfterThrowing(value = "controllerPointCut() && !logLoginPointCut()", throwing = "e")
    public void exceptionHandle(JoinPoint joinPoint, Exception e) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            //获取request
            HttpServletRequest request = attributes.getRequest();
            Method method = signature.getMethod();
            ReqPermissions reqPermissions = method.getAnnotation(ReqPermissions.class);
            String operation = "";
            if (reqPermissions != null) {
                operation = reqPermissions.operation();
            }
            SysLogVO sysLogVO = universalVOLoading((ProceedingJoinPoint) joinPoint, operation, request);
            sysLogVO.setType(LogType.THROW.getType());
            Map<String, Object> map = new HashMap<>();
            map.put("errorMessage", e.getMessage());//异常信息
            map.put("exceptionType", e.getClass().getName());//获取异常类型
            map.put("errorPath", joinPoint.getTarget().getClass().getName() + "." + signature.getName());//获取到出错的路径
            sysLogVO.setThrowInfo(JSON.toJSONString(map));
            sysLogVO.setStatus(0);
        }
    }

    /**
     * 生成SysLogVO各个属性的公共方法
     */
    private SysLogVO universalVOLoading(ProceedingJoinPoint joinPoint, String operation, HttpServletRequest request) {
        SysLogVO sysLogVO = new SysLogVO();
        //注解上的方法描述
        sysLogVO.setOperation(operation);
        //请求的参数
        Object[] args = joinPoint.getArgs();
        Object[] arguments = new Object[args.length];
        try {
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                    //ServletRequest不能序列化，从入参里排除，否则报异常：java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
                    //ServletResponse不能序列化 从入参里排除，否则报异常：java.lang.IllegalStateException: getOutputStream() has already been called for this response
                    continue;
                }
                arguments[i] = args[i];
            }
            String params = JSON.toJSONString(arguments);
            sysLogVO.setParams(params);
        } catch (Exception e) {
            log.error("获取请求参数发生错误");
            e.printStackTrace();
        }
        //ip
        sysLogVO.setIp(IpUtil.getIpAddr(request));
        //请求方式
        sysLogVO.setMethod(request.getMethod());
        //请求地址
        sysLogVO.setUri(request.getRequestURI());
        //用户账号
        sysLogVO.setPhone(JwtTokenUtil.getUserPhone(request));
        //用户名
        sysLogVO.setUsername(JwtTokenUtil.getUsername(request));
        return sysLogVO;
    }
}
